using UnityEngine;
using System.Collections;

public class Grunt : MonoBehaviour 
{
	public float fHealth = 3;
	public float fHealthMax = 3;
	public float fMoveSpeed;
	public float fVisualRange;
	public float fAttackTimer = 0;
	public float fAttackRange;
	public float gAttTimer = 0;
	
	// Private variables
	Vector3 vMoveDirection;
	CharacterController cController;
	GameObject oTarget;
	Vector3 vDestination;
	
	public GameObject gruntAttack;	
	
	// Use this for initialization
	void Awake () 
	{
		fMoveSpeed = 5;
		fVisualRange = 15;
		fAttackTimer = 0;
		fAttackRange = 2;
		
		// Get a reference to the Character Controller Component
		cController = gameObject.GetComponent<CharacterController>();
		oTarget = null;
		
		//gruntAttack = transform.FindChild("GruntAttack").gameObject;
		//gruntAttack.active = false;
	}
	
	// Update is called once per frame
	void Update () 
	{
		// Find object named Player
		oTarget = FindClosestObject(transform.position, "Player");
		
		Vector3 distance = (transform.position - oTarget.transform.position);
		
		vMoveDirection = new Vector3(0, 0, 0);
		
		if(distance.magnitude <= fVisualRange)
		{
			vDestination = oTarget.transform.position;
		}
		
		vMoveDirection = (vDestination - transform.position).normalized;
		vMoveDirection.y = 0;
		
		if(fAttackTimer <= 0 && distance.magnitude <= fAttackRange)
		{
			fAttackTimer = 100;
			gAttTimer = 5;
			//gruntAttack.active = true;
		}
		
		if(gAttTimer > 0)
		{
			gAttTimer--;
		}
		//else
			//gruntAttack.active = false;
		
		cController.Move(vMoveDirection * fMoveSpeed * Time.deltaTime);
		transform.rotation = Quaternion.LookRotation(vMoveDirection);
		
		fAttackTimer--;
	}
	
	
	GameObject FindClosestObject(Vector3 fromPosition, string tag) 
	{
		GameObject[] gos;
		gos = GameObject.FindGameObjectsWithTag(tag);
		GameObject closest = null;
		float distance = Mathf.Infinity;
		Vector3 position = fromPosition;
		
		foreach (GameObject go in gos) 
		{
			Vector3 diff = go.transform.position - position;
			float curDistance = diff.sqrMagnitude;
			if (curDistance < distance) 
			{
				closest = go;
				distance = curDistance;
			}
		}
		
		return closest;
	}
}
